package com.huihui;

import android.os.Build;
import android.os.StrictMode;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.huihui.bean.StsToken;
import com.huihui.datamanager.AppManager;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.network.base.RequestUtil;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.Contants;
import com.huihui.utils.CrashHandler;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePalApplication;

import java.util.Collections;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;

/**
 * Created by Administrator on 2018/8/7.
 */

public class MainApp extends LitePalApplication {

    private static MainApp gApp;
    public static StsToken stsToken;
    private static final Object gLock = new Object();
    private UserInfo mUserInfo;
    public static OSS oss;

    public static synchronized MainApp getIns() {
        synchronized (gLock) {
            return gApp;
        }
    }

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        mUserInfo = userInfo;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init(){
        gApp = this;
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        RequestUtil.init();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        AppManager.initAppManager(this);
        initPacasso();
        getStsToken();
        initWeibo();
    }

    private void initWeibo() {
        WbSdk.install(this,new AuthInfo(this, Contants.APP_KEY, Contants.REDIRECT_URL, Contants.SCOPE));
    }

    private void getStsToken() {
        OkHttpRequest.getInstance().getStsToken(HttpContants.getStsToken, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject != null && jsonObject.has(HttpContants.DATA)){
                        stsToken = AppManager.getGson().fromJson(jsonObject.getString(HttpContants.DATA),StsToken.class);
                        if(stsToken != null){
                            initAliyun(stsToken);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }




    private static void initAliyun(StsToken stsToken) {
        String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
        // 在移动端建议使用STS的方式初始化OSSClient，更多信息参考：[访问控制]
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(stsToken.getAccessKeyId(), stsToken.getAccessKeySecret(),stsToken.getSecurityToken());
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        oss = new OSSClient(MainApp.getIns().getApplicationContext(), endpoint, credentialProvider, conf);
    }

    private void initPacasso() {
        final OkHttpClient client = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .build();

        final Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(client))
                .build();
        Picasso.setSingletonInstance(picasso);

    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

}
